package org.middleware.controller.system;

import lombok.extern.slf4j.Slf4j;
import org.middleware.common.AuthenticationToken.RequireLogin;
import org.middleware.common.BusinessException;
import org.middleware.controller.common.CommonHttpResponse;
import org.middleware.entity.system.SysUsers;
import org.middleware.service.system.AvatarService;
import org.middleware.service.system.SysUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequireLogin
public class SysUsersController {
    @Autowired
    private SysUsersService usersService;

    @Autowired
    private AvatarService avatarService;

    @PostMapping("/register")
    public CommonHttpResponse register(@RequestBody SysUsers user) {
        try {
            SysUsers result = usersService.register(user);
            result.setPassword("");
            return CommonHttpResponse.success("注册成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("注册失败", e);
            return CommonHttpResponse.fail(500, "系统错误，请联系管理员");
        }
    }

    /**
     * 根据企业id和部门id查询用户信息
     * @param enterpriseId 企业id
     * @param departmentId 部门id
     * @return
     */
    @GetMapping("/users/enterprises/{enterpriseId}/departments/{departmentId}")
    public CommonHttpResponse getUsersByEnterpriseAndDepartment(@PathVariable int enterpriseId, @PathVariable int departmentId) {
        try{
            List<SysUsers> result = usersService.getUsersByEnterpriseAndDepartment(enterpriseId, departmentId);
            return CommonHttpResponse.success(result);
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("根据企业id和部门id查询用户失败", e);
            return CommonHttpResponse.fail(500, "根据企业id和部门id查询用户失败");
        }
    }

    /**
     * 用户登录
     *
     * @param user 用户信息
     * @return 公共http响应
     */
    @PostMapping("/login")
    public CommonHttpResponse login(@RequestBody SysUsers user) {
        try {
            Map<String, String> result = usersService.login(user);
            return CommonHttpResponse.success(result);
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("登录失败", e);
            return CommonHttpResponse.fail(500, "服务器异常，请联系管理员");
        }
    }

    /**
     * 根据用户名查询用户是否存在
     *
     * @param username 用户名
     * @return 0:不存在;1:存在
     */
    @GetMapping("/users/name/{username}")
    public CommonHttpResponse usernameIsExist(@PathVariable String username) {
        int exist = usersService.getUserByName(username) == null ? 0 : 1;
        return CommonHttpResponse.success(new HashMap<String, Integer>() {{
            put("exist", exist);
        }});
    }

    /**
     * 根据用户ID查询用户信息，排除超级管理员的查询
     *
     * @param id 用户id
     * @return 公共http响应
     */
    @GetMapping("/users/id/{id}")
    @RequireLogin
    public CommonHttpResponse getUserInfo(@PathVariable int id) {
        if (id <= 0) {
            return CommonHttpResponse.fail(400, "用户id小于等于0，非法");
        }
        try {
            SysUsers user = usersService.getUserById(id);
            user.setPassword("");
            user.setIsSuperAdmin(0);
            user.setAvatar(avatarService.getAvatarFile(user.getAvatar()));
            return CommonHttpResponse.success(user);
        } catch (Exception e) {
            log.error("ID查询用户失败", e);
            return CommonHttpResponse.fail(500, "服务器异常，请联系管理员");
        }
    }

    @PostMapping("/users")
    public CommonHttpResponse addUser(@RequestBody SysUsers user) {
        try {
            usersService.addUser(user);
            return CommonHttpResponse.success("新增用户成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e){
            log.error("新增用户信息异常:", e);
            return CommonHttpResponse.fail(500, "新增用户信息异常，请联系管理员");
        }
    }


    /**
     * 更新用户信息
     *
     * @param user 用户信息
     * @return 成功/失败的消息
     */
    @PutMapping("/users")
    public CommonHttpResponse updateUserInfo(@RequestBody SysUsers user) {
        try {
            usersService.updateUserInfo(user);
            return CommonHttpResponse.success("更新成功");
        } catch (BusinessException e) {
            return CommonHttpResponse.fail(400, e.getMessage());
        } catch (Exception e) {
            log.error("用户信息更新异常", e);
            return CommonHttpResponse.fail(500, "更新异常，请联系管理员");
        }
    }

    @PostMapping("/avatar/upload/{id}")
    public CommonHttpResponse avatarUpload(@PathVariable int id, @RequestParam MultipartFile file) {
        try {
            String url = avatarService.saveAvatar(id, file);
            Map<String, String> result = new HashMap<>();
            result.put("url", url);
            return CommonHttpResponse.success(result);
        } catch (IOException e) {
            log.error("头像上传失败,IO异常", e);
            return CommonHttpResponse.fail(500, "头像上传失败,请联系管理员排查");
        } catch (Exception e) {
            log.error("头像上传失败，其他异常", e);

            return CommonHttpResponse.fail(500, "头像上传失败,请联系管理员排查");
        }
    }


}
